import { useState, useEffect } from "react";
import { Button } from "antd";

let interval = null;
export default function Bar() {
  const [timer, setTimer] = useState(10);
  const [password, setPassword] = useState({});

  const fetchWord = () => {
    return new Promise((resolve, reject) => {
      resolve({
        code: 200,
        data: {
          word: "123456",
        },
        message: "获取成功",
      });
    });
  };

  const getPassWord = async () => {
    interval = setInterval(() => {
      setTimer((pre) => pre - 1);
    }, 1000);
    const result = await fetchWord();
    if (result.code === 200) {
      setPassword(result.data.word);
    }
  };

  useEffect(() => {
    if (timer === 0) {
      clearInterval(interval);
      setTimer(10);
    }
  }, [timer]);

  return (
    <Button type="primary" onClick={getPassWord}>
      {timer === 10 ? "获取验证码" : `${timer}S重试`}
    </Button>
  );
}
